<template>
  <LoginHeader>欢迎登录</LoginHeader>
  <section class="login-section">
    <div class="wrapper">
      <nav>
        <a href="javascript:;" @click="activeName='account'" :class="{active:activeName==='account'}">短信验证</a>
        <!-- <a href="javascript:;" @click="activeName='qrcode'" :class="{active:activeName==='qrcode'}">账户登录</a> -->
      </nav>
      <!-- 登录结构 -->
      <!-- 表单 -->
      <div v-if="activeName==='account'" class="account-box">
        <el-form
          ref="rule"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名:" prop="mobile">
            <el-input
              v-model="ruleForm.mobile"
              class="inp"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="code" class="form-item">
            <el-input
              v-model="ruleForm.code"
              class="inp1"
            > </el-input>
            <!-- <el-button round size="mini" class="code" @click="send">{{time===0?'发送验证码':`${time}秒后发送`}}</el-button> -->
          </el-form-item>
          <el-form-item prop="checked">
          <el-checkbox class="checkbox" v-model="ruleForm.checked">我已阅读并同意用户协议和隐私条款</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('rule')" class="btn">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 二维码 -->
      <div v-if="activeName==='qrcode'" class="qrcode-box">
        <!-- <img src="@/assets/images/qrcode.jpg" alt="">
        <p>打开 <a href="javascript:;">小兔鲜App</a> 扫码登录</p> -->
      </div>
    </div>
  </section>
  <LoginFooter />
</template>
<script>
import LoginHeader from './components/login-header.vue'
import LoginFooter from './components/login-footer.vue'
// import { useIntervalFn } from '@vueuse/core'
import { useAccountLogin } from '../../api/user'
import { ElMessage } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { reactive, ref } from 'vue-demi'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'Login',
  components: {
    LoginHeader,
    LoginFooter
  },
  setup () {
    const router = useRouter()
    const store = useStore()
    const route = useRoute()
    const activeName = ref('account')
    const ruleForm = reactive({
      mobile: '',
      code: '',
      checked: false
    })
    const rules = reactive({
      mobile: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { pattern: /^\w{6}$/, message: '长度必须为6为字母', trigger: 'blur' }],
      code: [{ required: true, message: '请输入密码', trigger: 'blur' }, { pattern: /^\d{6}$/, message: '长度必须为6位数字', trigger: 'blur' }],
      checked: [
        // value为验证的值   成功返回callback()
        {
          validator: (rule, value, callback) => {
          // console.log(value);
            if (value) {
              callback()
            } else {
              callback(new Error('请同意用户协议'))
            }
          },
          trigger: 'change'
        }
      ]
    })
    const { proxy } = getCurrentInstance()
    // console.dir(proxy)
    const submitForm = (formName) => {
      proxy.$refs[formName].validate(async (valid) => {
        if (valid) {
          // alert('submit!')
          try {
            const data = await useAccountLogin({ account: ruleForm.mobile, password: ruleForm.code })
            const { id, account, avater, nickname, mobile, token } = data.result
            // 更新用户信息
            store.commit('user/setUser', { id, account, avater, nickname, mobile, token })
            // 合并购物车
            store.dispatch('cart/mergeCart').then(() => {
              // console.log(route.query.redirect)
              // 401时 会重新登录这时会在login后面？redirect= 出错时所在的路径
              router.push(route.query.redirect || '/')
              ElMessage({
                message: '登录成功',
                type: 'success'
              })
            })
            // console.log(data)
          } catch (error) {
            if (error.response) {
              ElMessage({
                message: `登录失败:${error.response.data.message}`
              })
            }
            // console.dir(error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    // const time = ref(0)
    // const { pause, resume } = useIntervalFn(() => {
    //   time.value--
    //   console.log(time.value)
    //   if (time.value <= 0) {
    //     pause()
    //   }
    // }, 1000, { immediate:false })
    // onUnmounted(() => {
    //   pause()
    // })
    // 获取验证码
    // const send = async () => {
    // if (/^1[3|5|7|8|9]\d{9}$/.test(ruleForm.mobile)) {
    // if (time.value === 0) {
    // await useMobileLogin(ruleForm.mobile)
    // ElMessage('发送短信成功')
    // time.value = 60
    // // 开启定时器读秒
    // resume()
    // }
    // } else {
    //   ElMessage('手机号格式错误')
    // }
    // }
    return { activeName, ruleForm, submitForm, rules }
  }
}
</script>
<style scoped lang="less">
@import '../../assets/styles/variable.less';
.login-section {
  background: url(../../assets/images/login.png) no-repeat center / cover;
  height: 488px;
  position: relative;
  .wrapper {
    width: 380px;
    background: #fff;
    min-height: 300px;
    position: absolute;
    left: 50%;
    top: 54px;
    transform: translate3d(100px,0,0);
    box-shadow: 0 0 10px rgba(0,0,0,.15);
    // opacity: .9;
    nav {
      height: 55px;
      border-bottom: 1px solid #f5f5f5;
      // display: flex;
      padding-top: 20px;
      text-align: center;
      // align-items: center;
      a {
        // flex: 1;
        font-size: 25px;
        line-height: 1;
        display: inline-block;
        // font-size: 18px;
        position: relative;
        // &:first-child {
        //   border-right: 1px solid #f5f5f5;
        //   text-align: left;
        // }
        &.active{
          color: @c;
          font-weight: bold;
        }
      }
    }
  }
  .demo-ruleForm{
    // margin-left: -20px;
    padding: 20px
  }
  .btn{
    width: 80%;
    margin-left: -20px;
  }
  .checkbox{
    margin-left: -30px;
  }
  .inp{
    border-bottom: 1px solid rgb(168, 167, 167);
    width: 90%;
  }
  .form-item{
    position: relative;
    .inp1{
      border-bottom: 1px solid rgb(168, 167, 167);
      width: 90%;
    }
    .code{
      position: absolute;
      right: 30px;
      font-size: 8px;
      top: 8px;
      color: rgb(145, 144, 144);
    }
  }
}
</style>
